import 'package:flutter/material.dart';

import 'package:sow_app_core/sow_app_core.dart';
import 'package:sow_app_i18n/sow_app_i18n.dart';

import '../../../presenter/state_novel_detail_presenter.dart';
import '../../library/classify/tag_novel_page.dart';
import 'chapter_detail_page.dart';

class NovelDetailPage extends StatefulWidget {
  static const routeName = '/novel_detail';
  const NovelDetailPage(
      {Key? key, required this.controller, required this.presenter})
      : super(key: key);

  final NovelDetailController controller;
  final StateNovelDetailPresenter presenter;
  @override
  State<NovelDetailPage> createState() => _NovelDetailPageState();
}

class _NovelDetailPageState extends State<NovelDetailPage> {
  String filterText = '';
  @override
  void initState() {
    widget.presenter.presenterContext = context;
    widget.presenter.presenterSetState = setState;
    Future.delayed(Duration.zero)
        .then((value) => ModalRoute.of(context)?.settings.arguments as String)
        .then((novelId) {
      widget.presenter.novelId = novelId;
      widget.controller.init();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.presenter.novel?.title ?? I18n.loading),
        actions: [
          IconButton(
              onPressed: () {
                widget.controller.subscribe();
              },
              icon: widget.presenter.inShelf
                  ? const Icon(Icons.library_add_check)
                  : const Icon(Icons.library_add))
        ],
      ),
      body: Builder(builder: (context) {
        return widget.presenter.novel == null
            ? const Text(I18n.loading)
            : Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Row(
                      children: [
                        Image.network(
                          widget.presenter.novel!.cover,
                          height: 160,
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    widget.presenter.novel!.title,
                                    style:
                                        Theme.of(context).textTheme.titleLarge,
                                  ),
                                  Text(
                                    widget.presenter.novel!.author,
                                    style:
                                        Theme.of(context).textTheme.titleSmall,
                                  ),
                                  Text(
                                    widget.presenter.novel!.bookStatus! ==
                                            I18n.book_status_going_value
                                        ? I18n.book_status_going
                                        : I18n.book_status_end,
                                    style:
                                        Theme.of(context).textTheme.bodySmall,
                                  ),
                                  Text(
                                    "${widget.presenter.novel!.score}分",
                                    style:
                                        Theme.of(context).textTheme.bodySmall,
                                  ),
                                  Text(
                                    "${widget.presenter.novel!.visitCount!}阅读",
                                    style:
                                        Theme.of(context).textTheme.bodySmall,
                                  ),
                                  Text(
                                    '${(int.parse(widget.presenter.novel!.wordCount!) / 10000).ceil()}万字',
                                    style:
                                        Theme.of(context).textTheme.bodySmall,
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: widget
                                        .presenter.novel!.novelTypeList
                                        .map((e) => TextButton(
                                            onPressed: () {
                                              Navigator.pushNamed(context,
                                                  TagNovelListPage.routeName,
                                                  arguments: e);
                                            },
                                            child: Text(
                                              e.classifyName,
                                            )))
                                        .toList(),
                                  ),
                                ]),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '热门评论',
                          style: Theme.of(context).textTheme.titleLarge,
                        ),
                        TextButton(
                            onPressed: () {
                              showDialog(
                                  context: context,
                                  builder: (context) {
                                    return Dialog(
                                      child: SizedBox(
                                        width: 200,
                                        child: Padding(
                                          padding: const EdgeInsets.all(8.0),
                                          child: TextField(
                                            maxLength: 32,
                                            decoration: const InputDecoration(
                                                prefixIcon: Icon(Icons.comment),
                                                label: Text(I18n.add_comment)),
                                            onSubmitted: (value) {
                                              widget.presenter.comment = value;
                                              widget.controller
                                                  .addComment()
                                                  .then((value) =>
                                                      Navigator.pop(context));
                                            },
                                          ),
                                        ),
                                      ),
                                    );
                                  });
                            },
                            child: const Text('发布评论')),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8.0),
                    child: SizedBox(
                      height: 32,
                      child: widget.presenter.commentList.isEmpty
                          ? Center(
                              child: Icon(
                              Icons.no_meals,
                              color: Colors.grey.shade400,
                            ))
                          : ListView(
                              scrollDirection: Axis.horizontal,
                              children: widget.presenter.commentList
                                  .map((e) => Padding(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 8.0),
                                        child: Text(e.content),
                                      ))
                                  .toList(),
                            ),
                    ),
                  ),
                  Expanded(
                    child: DefaultTabController(
                        length: 2,
                        child: Column(
                          children: [
                            Align(
                              alignment: Alignment.centerLeft,
                              child: TabBar(isScrollable: true, tabs: [
                                Tab(
                                  child: Text(
                                    '最新章节',
                                    style:
                                        Theme.of(context).textTheme.titleLarge,
                                  ),
                                ),
                                Tab(
                                  child: Text(
                                    '全部章节',
                                    style:
                                        Theme.of(context).textTheme.titleLarge,
                                  ),
                                )
                              ]),
                            ),
                            Expanded(
                              child: TabBarView(children: [
                                ListView(
                                    children:
                                        _getChapterList('').take(10).toList()),
                                Column(
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 8.0),
                                      child: TextField(
                                        decoration: const InputDecoration(
                                          prefixIcon: Icon(Icons.search),
                                        ),
                                        onChanged: (value) {
                                          setState(() {
                                            filterText = value;
                                          });
                                        },
                                      ),
                                    ),
                                    Expanded(
                                      child: ListView(children: [
                                        ..._getChapterList(filterText)
                                            .reversed
                                            .toList()
                                      ]),
                                    ),
                                  ],
                                ),
                              ]),
                            )
                          ],
                        )),
                  ),
                ],
              );
      }),
    );
  }

  List<ListTile> _getChapterList(String filterText) =>
      widget.presenter.chapterList
          .where((element) =>
              filterText.isEmpty ? true : element.title!.contains(filterText))
          .map(
        (e) {
          return ListTile(
            onTap: () {
              widget.controller.addReadHistory();
              Navigator.pushNamed(context, ChapterDetailPage.routeName,
                  arguments: e);
            },
            title: Text(e.title ?? ""),
          );
        },
      ).toList();
}
